package com.loop.unclelend.ui.activity

import android.annotation.SuppressLint
import android.graphics.Color
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import com.loop.unclelend.R
import com.loop.unclelend.base.app.AppStackManager
import com.loop.unclelend.databinding.UiLoginBinding
import com.loop.unclelend.pro.ProActivity
import com.loop.unclelend.ui.presenter.Pre_Login
import com.loop.unclelend.ui.view.IView_Login
import com.loop.unclelend.utils.BarUtil
import com.loop.unclelend.utils.DensityUtils
import com.loop.unclelend.utils.event.UncleEventHelper
import com.loop.unclelend.utils.event.UncleEventType
import com.loop.unclelend.utils.helper.SharedHelper
import com.loop.unclelend.utils.thread.TimingThread
import org.json.JSONObject

/**
 * UncleLend
 * @Author wwdeng
 * @CreateTime: 2024/9/4 18:23
 * @Annotation：登录
 */
class Act_Login: ProActivity(),IView_Login, TimingThread.ITimingThreadListener {
    lateinit var binding: UiLoginBinding
    private var presenter: Pre_Login? = null

    //倒计时
    private var countdown = 60
    private var timeThread: TimingThread? = null

    override fun getUncleRootView(): View {
        binding = UiLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initUncleView() {
        binding.layoutLogin.setPadding(DensityUtils.dp2px(16f),BarUtil.getStatusBarHeight(),DensityUtils.dp2px(16f),0)

        //关闭所有页面
        AppStackManager.finishAllActivity(Act_Login::class.java)
        checkLoginBtnState()
        binding.imgMobileTrue.visibility = View.GONE
    }

    override fun initUncleListener() {
        binding.editMobile.setOnFocusChangeListener { v, hasFocus ->
            when(hasFocus){
                true -> {

                }
                else -> {
                    UncleEventHelper.addUncleRequestEventAction(UncleEventType.FORM.UNCLE_FORM_LOGIN_MOBILE, getMobile())
                }
            }
        }
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                binding.imgMobileTrue.visibility = View.GONE
                checkLoginBtnState()
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //验证码入框监听
        binding.editCode.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                checkLoginBtnState()
            }
        })

        //隐私政策切换
        binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
            checkLoginBtnState()
            when (isChecked) {
                true -> {
                    UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_LOGIN_PRIVACY_AGREE)
                }
                false -> {
                    UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_LOGIN_PRIVACY_DENY)
                }
            }
        }

        //发送验证码
        binding.btnSend.setOnClickListener {
            UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_LOGIN_GETCODE)
            binding.editMobile.clearFocus()

            showUncleLoading()
            //发送验证码
            presenter!!.requestSendSmsCodeAction()
        }

        //登录
        binding.btnLogin.setOnClickListener {
            UncleEventHelper.addUncleRequestEventAction(UncleEventType.CLICK.UNCLE_CLICK_LOGIN_NEXT)
            onHideSoftInput(binding.editCode)
            showUncleLoading()
            presenter!!.requestLoginAction(getMobile(),getCode(),"NO")
        }

        //协议
        binding.txtPrivacyPolicy.setOnClickListener {
            onIntent(Act_PrivacyPolicy::class.java)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initUncleData() {
        binding.txtZoneCode.text = "+${SharedHelper.getUncleSPString(SharedHelper.UNCLE_SPKEY.UNCLE_TIMEZONE_CODE)}"
//        binding.textZoneCode.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
//        binding.textZoneCode.paint.isAntiAlias = true//抗锯齿

        val showText = String.format(getString(R.string.login_privacy_policy),getString(R.string.privacy_policy_title))
        val spString = SpannableString(showText)
        val start = showText.indexOf(getString(R.string.privacy_policy_title))
        spString.setSpan(ForegroundColorSpan(Color.parseColor("#FF000000")), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //添加下划线
        spString.setSpan(UnderlineSpan(), start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.txtPrivacyPolicy.text = spString

        presenter = Pre_Login(this)
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkLoginBtnState() {
        if (binding.checkBox.isChecked && getMobile().isNotEmpty() && getCode().isNotEmpty() && getCode().length >= 4) {
            binding.btnLogin.isEnabled = true
        } else {
            binding.btnLogin.isEnabled = false
        }
        checkEditCodeDefaultState()
        checkSendBtnState()
    }

    /**
     * 设置验证码输入框为正常状态
     */
    private fun checkEditCodeDefaultState(){
        binding.editCode.setTextColor(Color.parseColor("#000000"))
        binding.editCode.setBackgroundResource(R.drawable.radius_fill_ffe6e4e9_8)
        binding.layoutCodeWrong.visibility = View.GONE
    }

    /**
     * 设置发送验证码按钮状态
     */
    private fun checkSendBtnState(){
        if (getMobile().isNotEmpty() && countdown == 60){
            binding.btnSend.isEnabled = true
        } else {
            binding.btnSend.isEnabled = false
        }
    }

    /**
     * 获取电话号码
     */
    override fun getMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    /**
     * 获取验证码
     */
    override fun getCode(): String {
        return binding.editCode.text.toString().trim()
    }

    /**
     * 验证码发送成功
     */
    override fun showSenCodeSuccess() {
        binding.imgMobileTrue.visibility = View.VISIBLE
        checkEditCodeDefaultState()

        startTimeThread()
    }

    override fun showLoginFailure(data: JSONObject) {
        binding.editCode.setBackgroundResource(R.drawable.uncle_login_code_wrong)
        binding.editCode.setTextColor(Color.parseColor("#FFF86F00"))
        binding.layoutCodeWrong.visibility = View.VISIBLE
    }

    override fun showMainPage() {
        //停止倒计时
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        onIntent(Act_Main::class.java)
        finish()
    }

    /**
     * 启动倒计时
     */
    private fun startTimeThread() {
        if (timeThread != null) {
            timeThread!!.stopThread()
        }
        countdown = 60
        checkSendBtnState()
        if (timeThread == null) {
            timeThread = TimingThread()
            timeThread!!.setThreadDelayMillis(1000)
            timeThread!!.setLoadListener(this)
        }
        timeThread!!.startThread()
    }

    @SuppressLint("SetTextI18n")
    override fun onLoading() {
        if (countdown <= 1) {
            countdown = 60
            checkSendBtnState()
            timeThread!!.stopThread()
            binding.btnSend.text = getString(R.string.login_resend)
            return
        }
        countdown--
        binding.btnSend.text = "${countdown}S"
        checkSendBtnState()
    }

    override fun onStart() {
        super.onStart()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_LOGIN_START)
    }

    override fun onDestroy() {
        super.onDestroy()
        UncleEventHelper.addUncleRequestEventAction(UncleEventType.PAGE.UNCLE_PAGE_LOGIN_END)
        if (timeThread != null) {
            timeThread!!.stopThread()
            timeThread = null
        }
    }
}